#include "cv.h"
#include <highgui.h>
#include <stdio.h>
//int **matrix,*p_matrix;
int matrix[2000][2000];
int main(int argc,char **argv){
	IplImage *in=cvLoadImage(argv[1],0),
		 *out;
	int x,y,i;
	int w=in->width,h=in->height;
	int start_line=0,end_line=h-1;
	int mode=1,found=0;

	/*
	matrix=(int **)malloc(h*sizeof(int *)+h*w*sizeof(int));
	for(i=0,p_matrix=(int *)(matrix+h);i<h;i++,p_matrix+=w)
		matrix[i]=p_matrix;
	*/

	unsigned char *ptr;
	for(y=0;y<h;y++){
		ptr=(unsigned char *)(in->imageData+in->widthStep*y);
		for(x=0;x<w;x++)
			matrix[y][x]=ptr[x];
	}
	for(y=0;y<h;y++){
		for(x=0;x<w;x++)
			if(matrix[y][x]<128){
				start_line=y;
				found=1;
				break;
			}
		if(found)	break;
	}
	found=0;
	for(y=h-1;y>=0;y--){
		for(x=0;x<w;x++)
			if(matrix[y][x]<128){
				end_line=y;
				found=1;
				break;
			}
		if(found)	break;
	}
	printf("start_line=%d\tend_line=%d\n",start_line,end_line);
	if(start_line<end_line)
		cvSetImageROI(in,cvRect(0,start_line,w,end_line-start_line));
	out=cvCreateImage(cvSize(w,end_line-start_line),in->depth,in->nChannels);
	cvCopy(in,out,0);
	char filename[30];
	sprintf(filename,"area_third_%s.jpg",argv[2]);
	cvSaveImage(filename,out,0);
	cvResetImageROI(in);
	cvReleaseImage(&in);
	//cvReleaseImage(&out);
	return 0;
}
